package com.example.springbootdemo.controller;

import com.example.springbootdemo.entity.Product;
import com.example.springbootdemo.entity.User;
import com.example.springbootdemo.service.ProductService;
import com.example.springbootdemo.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @ClassName: CommonController
 * @Description:
 * @Author: TXW
 * @Date: 2025/1/10
 */
@Log4j2
@RestController
@RequestMapping("test")
public class CommonController {

    @Resource
    private UserService userService;
    @Resource
    private ProductService productService;
    @RequestMapping("hello")
    public String hello(HttpServletRequest request){
        log.info("请求头：{} ",request);
        return request.toString();
    }

    /**
     *
     * 查询所有用户
     * */
    @RequestMapping("user")
    public List<User> user() throws UnknownHostException {
        log.info("服务器：{} 获取所有用户",InetAddress.getLocalHost());
        return userService.getAllUser();
    }

    /**
     * 获取某件商品
     * */

    @GetMapping("/product/{id}")
    public Product getProduct(@PathVariable Integer id) {
        return productService.getProduct(id);
    }


    /**
     *
     * 模拟秒杀某个商品接口
     * */
    @GetMapping("/product/dis/{id}")
    public String disProduct(@PathVariable Integer id, HttpServletRequest request) throws UnknownHostException {
        String requestedSessionId = request.getRequestedSessionId();
        return productService.disProduct(id);
    }

    @PostMapping("/product/update")
    public String disProduct(@RequestBody Product product){
        return productService.update(product) != 0 ? "更新成功" : "更新失败";
    }

    /**
     * 初始化商品数量，缓存
     * */
    @GetMapping("/product/init/{id}")
    public String initProduct(@PathVariable Integer id) {
        return productService.initProduct(id);
    }

}
